import * as CryptoJS from 'crypto-js';

import { Constant } from '@core/constant';

const ivContext = CryptoJS.enc.Utf8.parse(Constant.AESIVCONTEXT);

export const AES = {
    encrypt: (word: string, key: string): string => {
        const keyHex = CryptoJS.enc.Utf8.parse(key);
        const encrypted = CryptoJS.AES.encrypt(word, keyHex, {
            iv: ivContext,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    },
    decrypt: (word: string, key: string): string => {
        const keyHex  = CryptoJS.enc.Utf8.parse(key);
        const decrypted = CryptoJS.AES.decrypt({
            ciphertext: CryptoJS.enc.Base64.parse(word),
            salt: '',
            iv: ivContext
        }, keyHex, {
            iv: ivContext,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    }
};

export const SHA = {
    sha1: (word: string): string => {
        return CryptoJS.SHA1(word).toString();
    }
};

export const MD5 = (str: string): string => {
    return CryptoJS.MD5(str).toString();
};
